package bb.lanxing.mvp.model;

import bb.lanxing.model.WorkoutDatabaseHelper;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.mvp.model.i.IWorkoutMergeModel;
import java.util.List;
import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class WorkoutMergeModelImpl implements IWorkoutMergeModel {
    @Override
    public Observable<Workout> queryWorkout(Long[] workoutIds) {
        return Observable.from(workoutIds).subscribeOn(Schedulers.io()).flatMap(new Func1<Long, Observable<Workout>>() {
            @Override
            public Observable<Workout> call(Long id) {
                Workout queryWorkoutById = WorkoutDatabaseHelper.queryWorkoutById(id);
                if (queryWorkoutById == null) {
                    return Observable.error(new IllegalStateException("Workout not find !"));
                }
                List<Trackpoint> queryTrackPointForMap = WorkoutDatabaseHelper.queryTrackPointForMap(id, queryWorkoutById.getLocSource());
                if (queryTrackPointForMap == null || queryTrackPointForMap.isEmpty()) {
                    return Observable.error(new IllegalStateException("workout point not found, please download first !"));
                }
                queryWorkoutById.setTrackPoints(queryTrackPointForMap);
                return Observable.just(queryWorkoutById);
            }
        });
    }
}
